package com.kedacom.freedomLabel.view.activity.server;


import android.util.Log;

import com.kedacom.freedomLabel.model.bean.SharedFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.List;

import fi.iki.elonen.NanoHTTPD;

public class FileDownLoadUtil extends NanoHTTPD {

    public FileDownLoadUtil(int port) {
        super(port);
    }

    public static final int DEFAULT_SERVER_PORT = 8080;
    public static final String TAG = FileDownLoadUtil.class.getSimpleName();
    private static final String REQUEST_ROOT = "/";
    private List<SharedFile> fileList;


    public FileDownLoadUtil(List<SharedFile> fileList) {
        super(DEFAULT_SERVER_PORT);
        this.fileList = fileList;
    }

    public List<SharedFile> getFileList() {
        return fileList;
    }

    public void setFileList(List<SharedFile> fileList) {
        this.fileList = fileList;
    }

    public void addSharedFile(SharedFile file) {
        Iterator<SharedFile> iterator = fileList.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().equal(file)) {
                return;
            }
        }
        fileList.add(file);
    }

    public void removeSharedFile(SharedFile file) {
        Iterator<SharedFile> iterator = fileList.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().equal(file)) {
                iterator.remove();
                break;
            }
        }
    }

    @Override
    public Response serve(IHTTPSession session) {
        Log.d(TAG, "OnRequest: " + session.getUri());
        if (REQUEST_ROOT.equals(session.getUri()) || session.getUri().equals("")) {
            return responseRootPage(session);
        }
        return responseFile(session);
//        return response404(session,session.getUri());
    }

    //对于请求根目录的，返回分享的文件列表
    public Response responseRootPage(IHTTPSession session) {
        StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPER html lang=\"zh-CN\"><html><body>");
        builder.append("<ol>");
        builder.append("<h2>文件数量：").append(fileList.size()).append("</h2>");
        for (int i = 0, len = fileList.size(); i < len; i++) {
            File file = new File(fileList.get(i).getPath());
            if (file.exists()) {
                //文件及下载文件的链接，定义了一个文件类，这里使用getPath方法获得路径，使用getName方法获得文件名
                builder.append("<li> <a href=\"").append(file.getPath()).append("\">").append(file.getName()).append("</a></li>");
            }
        }
        builder.append("</ol>");
        builder.append("</body></html>\n");
        //回送应答
        return new Response(Response.Status.OK,"text/html; charset=UTF-8",String.valueOf(builder));
    }

    //对于请求文件的，返回下载的文件
    public Response responseFile(IHTTPSession session) {
        try {
            //uri：用于标示文件资源的字符串，这里即是文件路径
            String uri = session.getUri();
            FileInputStream fis = new FileInputStream(uri);
            return new Response(Response.Status.OK, "application/octet-stream", fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return response404(session, null);
    }

    public Response response404(IHTTPSession session, String url) {
        StringBuilder builder = new StringBuilder();
        builder.append("<!DOCTYPE html><html><body>");
        builder.append("Sorry, Can't Found " + url + " !");
        builder.append("</body></html>\n");
        return new Response(Response.Status.NOT_FOUND, "text/html; charset=UTF-8", builder.toString());
    }

}
